package com.utility.bytehex;

public class ByteHexUtility {
	/**
	 * 字节码转十六进制字符串
	 * @param sources
	 * 		字节码
	 * @return
	 */
	public static String byteToHex(byte[] sources) {
		if(sources == null || sources.length == 0){
			return null;
		}
		StringBuffer result = new StringBuffer();
		for(byte source : sources){
			String tmp = (Integer.toHexString(source & 0XFF));
			if(tmp.length() == 1){
				result.append("0" + tmp);
			}else{
				result.append(tmp);
			}
		}
		return result.toString().toUpperCase();
	}
	
	/**
	 * 十六进制字符串转字节码
	 * @param source
	 * 		十六进制字符串
	 * @return
	 * @throws Exception
	 */
	public static byte[] hexToByte(String source) throws Exception {
		if(source.length() % 2 != 0){
			throw new IllegalArgumentException("给定的十六进制字符串的长度不是偶数");
		}
		char[] sourceChars = source.toUpperCase().toCharArray();
		int length = sourceChars.length/2;
		byte buffer[] = new byte[length];
		for(int index = 0;index < length;index++) {
			buffer[index] = (byte) (HEX_SOURCE.indexOf(sourceChars[index*2]) << 4 | HEX_SOURCE.indexOf(sourceChars[index*2 + 1]));
		}
		return buffer;
	}
	/**
	 * 十六进制字符
	 */
	private static final String HEX_SOURCE = "0123456789ABCDEF";
}
